package com.shire.shire_interface.controller.group;

import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.constants.Constants;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.model.group.*;
import com.shire.shire_interface.service.group.WxGroupMemberService;
import com.shire.shire_interface.service.group.WxGroupService;
import com.shire.shire_interface.service.group.impl.WxGroupQrcodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;


//@Api(tags = "取指定群的二维码")
@RestController
@RequestMapping("/group")
public class WxGroupController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private WxGroupService wxGroupService;
    @Resource
    private WxGroupMemberService wxGroupMemberService;
    @Resource
    private WxGroupQrcodeService qrcodeService;

    @ResponseBody
    @PostMapping("/groupInviteHistory")
    public Response getGroupInviteHistory(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            Integer csId = jsonObject.getInteger("csId");
            String wxAccount = jsonObject.getString("wxAccount");
            String groupNo = jsonObject.getString("groupNo");
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            List<VGroupInviteHistory> list = wxGroupService.getInviteHistoryDetail(groupNo,wxAccount);

            Map<String, Set<String>> retmap = new HashMap<>();

            for (VGroupInviteHistory item : list){
                String key = item.getInviterNick()+"("+item.getInviterWxid()+")";
                String value = item.getInviteeNick()+"("+item.getInviteeWxid()+")";
                if (!retmap.containsKey(key)){
                    retmap.put(key, new HashSet<>());
                }
                retmap.get(key).add(value);
            }
            response.setData(retmap);

        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }

    @ResponseBody
    @PostMapping("/groupQrcode")
    public Response getGroupQrcode(@RequestBody JSONObject jsonObject, HttpSession session){{
        Response response = new Response();
        try {
            Integer csId = jsonObject.getInteger("csId");
            String wxAccount = jsonObject.getString("wxAccount");
            String groupNo = jsonObject.getString("groupNo");
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxGroupQrcode qrcode = qrcodeService.getGroupQrcode(wxAccount,groupNo);
            if (qrcode == null){
                response.error("当前群没有二维维码，请刷同步通信录后再试！");
            }else {
                response.setData(qrcode.getQrcode());
                response.success("成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }}

//    @ApiOperation(value = "群的基本信息 csId, wxAccount, groupNo")
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @ResponseBody
    @PostMapping("/groupInfo")
    public Response groupInfo(@RequestBody JSONObject jsonObject, HttpSession session){
        Response response = new Response();
        try {
            Integer csId = jsonObject.getInteger("csId");
            String wxAccount = jsonObject.getString("wxAccount");
            String groupNo = jsonObject.getString("groupNo");
            if (!checkLoginUserByCsId(session, csId)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            WxGroupExample wxGroupExample = new WxGroupExample();
            wxGroupExample.createCriteria().andWxaccountEqualTo(wxAccount).andGroupnoEqualTo(groupNo);

            List<WxGroup> wxGroups = wxGroupService.selectByExample(wxGroupExample);

            if (wxGroups.size()>0){
                WxGroup wxGroup = wxGroups.get(0);
                response.setData(wxGroup);
            }
            response.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }

//    @ApiOperation(value = "微信账号下所有的群 csId  wxaccount")
//    @ApiImplicitParams(value ={
//            @ApiImplicitParam(paramType = "body", dataType = "WxGroup", name = "wxGroup")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @ResponseBody
    @PostMapping("/groups")
    public Response allGroups(@RequestBody WxGroup wxGroup, HttpSession session) {
        Response result = new Response();
        if (wxGroup.getWxaccount() == null){
            result.error("参数错误");
            return result;
        }
        try {
            if (!checkLoginUserByCsId(session, wxGroup.getCsid())){
                result.error("请登录！");
                result.setCode(501);
                return result;
            }
            WxGroupExample example = new WxGroupExample();
            example.createCriteria().andWxaccountEqualTo(wxGroup.getWxaccount()).andStatusEqualTo(Constants.CommonStatus.ENABLE.getCode());
            List<WxGroup> groups = wxGroupService.getAllGroups(example);
            result.setData(groups);
            result.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error("失败");
            logger.error("新建群消息 获取所有群异常");
        }
        return result;
    }

//    @ApiOperation(value = "查找指定成员所在的所有当前帐号为管理员的群 post body 传参数 csId  wxaccount memberWxId")
//    @ApiImplicitParams(value ={
//            @ApiImplicitParam(paramType = "body", dataType = "WxGroup", name = "wxGroup")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @ResponseBody
    @PostMapping("/groupsForMemeber")
    public Response allAdminGroupsForMember(@RequestBody JSONObject jsonObject, HttpSession session) {
        Response result = new Response();
        try {
            Integer csId = jsonObject.getInteger("csId");
            String wxAccount = jsonObject.getString("wxAccount");
            String memberWxId = jsonObject.getString("memberWxId");

            if (!checkLoginUserByCsId(session, csId)){
                result.error("请登录！");
                result.setCode(501);
                return result;
            }

            WxGroupMemberExample memberExample = new WxGroupMemberExample();
            memberExample.createCriteria().andWxaccountEqualTo(wxAccount).andWxidEqualTo(memberWxId);

            List<WxGroupMember> members = wxGroupMemberService.selectByExample(memberExample);
            List<String> groupNos = new ArrayList<>();
            for (WxGroupMember member : members) {
                if (!groupNos.contains(member.getGroupno())){
                    groupNos.add(member.getGroupno());
                }
            }

            WxGroupExample groupExample = new WxGroupExample();
            groupExample.createCriteria().andWxaccountEqualTo(wxAccount).andGroupnoIn(groupNos).andIsfirstEqualTo(1);

            List<WxGroup> groupList = wxGroupService.getAllGroups(groupExample);

            result.setData(groupList);
            result.success("成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.error("失败");
            logger.error("新建群消息 获取所有群异常");
        }
        return result;
    }
}
